//app.js

// "GateWay": "https://testwxappgw.cx580.com/GateWay.aspx",  //test

// "GateWay": "https://wxapplet.cx580.com/GateWay.aspx",  //车行易网关

//var Host = "http://14.23.146.234:7000/emsc-pub-api";  //测试

//var Host = "http://192.168.11.63:7001/emsc-pub-api";    ///本地

var Host = "https://emsc.cx580.com/emsc-pub-api";

//var Host = "http://emsc.cx580.com:8093/emsc-pub-api"; //体验

//develop（开发版），trial（体验版），release（正式版）
var FootConvenientService = {
	appid: 'wxc1257fe34b8d3264',
	path: '',
	envVersion: 'release'
};
App({
  globalData: {
//  "GateWay": "https://testwxappgw.cx580.com/GateWay.aspx",  //test
    "GateWay": Host,
    appid: FootConvenientService.appid,
    envVersion: FootConvenientService.envVersion,
    userInfo: null,
    isAuthSuccess:false,
    channelId: "",
    hintAuthorize: false,
    furtherProperties: {
      "CarOwnerLen": {
        "key": "CarOwnerLen",
        "display": "车主姓名",
        "value": "",
        "types": "text",
        "maxlength": 20,
        "placeholder": "请输入车主姓名"
      },
      "CarCodeLen": {
        "key": "CarCodeLen",
        "display": "车身架号",
        "value": "",
        "types": "text",
        "maxlength": 99,
        "placeholder": "请输入车身架号"
        
      },
      "CarDriveLen": {
        "key": "CarDriveLen",
        "display": "发动机号",
        "value": "",
        "types": "text",
        "maxlength": 99,
        "placeholder": "请输入发动机号"
      },
      "DrivingLicense": {
        "key": "DrivingLicense",
        "display": "行驶证正页图片",
        "value": "",
        "types": "img"
      },//行驶证正页复印件图片的URL
      "DrivingSecondLicense": {
        "key": "DrivingSecondLicense",
        "display": "行驶证副页图片",
        "value": "",
        "types": "img"
      },//行驶证副页复印件图片的URL
      "MajorViolation": {
        "key": "MajorViolation",
        "display": "驾驶证正页图片",
        "value": "",
        "types": "img"
      },//驾驶证正页复印件图片的URL
      "MajorSecondViolation": {
        "key": "MajorSecondViolation",
        "display": "驾驶证副页图片",
        "value": "",
        "types": "img"
      }, //驾驶证副页复印件图片的URL
      "OwnerCardLen": {
        "key": "OwnerCardLen",
        "display": "车主身份证号",
        "value": "",
        "types": "idcard",
        "maxlength": 18,
        "placeholder": "请输入车主身份证号",
        "pattern": /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/
      },
      "JashiZhengHaoLen": {
        "key": "JashiZhengHaoLen",
        "display": "驾驶证号",
        "value": "",
        "types": "idcard",
        "maxlength": 18,
        "placeholder": "请输入驾驶证号",
        "pattern": /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/
      },
      "XingShiZhengHaoLen": {
        "key": "XingShiZhengHaoLen",
        "display": "行驶证档案编号",
        "value": "",
        "types": "text",
        "maxlength": 25,
        "placeholder": "请输入行驶证档案编号"
      },
      "CheliangZhengShuLen": {
        "key": "CheliangZhengShuLen",
        "display": "车辆登记证书号",
        "value": "",
        "types": "text",
        "maxlength": 25,
        "placeholder": "请输入车辆登记证书号"
      },
      "DanganBianHaoLen": {
        "key": "DanganBianHaoLen",
        "display": "驾驶证档案编号",
        "value": "",
        "types": "text",
        "maxlength": 25,//12
        "placeholder": "请输入驾驶证档案编号"
      },
      "CarOwnerPhoneLen": {
        "key": "CarOwnerPhoneLen",
        "display": "车主联系电话",
        "value": "",
        "types": "number",
        "maxlength": 11,
        "placeholder": "请输入车主联系电话",
        "pattern": /^1(3|4|5|7|8)\d{9}$/
      },
      "TiaoXingMaLen": {
        "key": "TiaoXingMaLen",
        "display": "驾驶证条形码",
        "value": "",
        "types": "text",
        "maxlength": 25,
        "placeholder": "请输入驾驶证条形码"
      },
      "VerifyCodeLen": {
        "key": "VerifyCodeLen",
        "display": "验证码",
        "value": "number",
        "maxlength": 6,
        "placeholder": "请输入验证码"
      },
      "FilePhoneLen": {
        "key": "FilePhoneLen",
        "display": "驾驶证登记电话",
        "value": "",
        "types": "number",
        "maxlength": 11,
        "placeholder": "请输入驾驶证登记电话",
        "pattern": /^1(3|4|5|7|8)\d{9}$/
      }
    }
  },
  onLaunch: function () {
    console.log('什么也没做，纯输出onLaunch');
    //当小程序初始化完成时，会触发 onLaunch（全局只触发一次）
    //this.getUserInfo();
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.userInfo" 这个 scope
    if (wx.getSetting) {
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.userInfo']) {
            wx.authorize({
              scope: 'scope.userInfo',
              success() {
                // 用户已经同意小程序使用功能，后续调用 wx.getUserInfo 接口不会弹窗询问
                wx.getUserInfo()
              }
            })
          }
        }
      })
    }else {
      console.log('用户是否授权：没有wx.getSetting功能');
    } 

    
  },
  onShow: function () {
    //当小程序启动，或从后台进入前台显示，会触发 onShow

  },
  onHide: function () {
    //当小程序从前台进入后台，会触发 onHide
  },
  onError: function (msg) {
    //当小程序发生脚本错误，或者 api 调用失败时，会触发 onError 并带上错误信息
    console.log('小程序发生脚本错误onError',msg);
  },

  //后台保存用户信息
  setUserInfo: function (parameter) {
	  //加载车辆信息
	  var param = {
		  url: '/wx/carViola/uwu.ajax',
		  para: parameter
	  };
	  this.requestSdkForNeedLogin({
			  param: param,
			  beforeSend: function(data) {
          //发送请求之前执行
          wx.showToast({
            title: '请稍候',
            icon: 'loading',
            duration: 10000
           });
       },
      success: function(data){

      },
      complete: function(data) {
        wx.hideToast();
      }
     });
  },

  toastAuthFailModal:function () {
    wx.showModal({
        title: '微信认证失败',
        content: '请退出“邮证查违章”，然后再次进入，重新获取微信认证。',
        showCancel: false,
        success: function (res) {
            if (res.confirm) {
                console.log('用户点击确定');
            } else if (res.cancel) {
                console.log('用户点击取消');
            }
        }
    });
  },

  getUserInfo: function (callback) {
    //获取用户信息
    var that=this;
    if (this.globalData.userInfo) {
      typeof callback == "function" && callback(that.globalData.userInfo);
    } else {
      //调用登录接口
      wx.login({
        success: res => {
          var code = res.code;
          wx.getUserInfo({
            success: res => {
              var param = {
                  url: '/wx/carViola/eo.ajax',
                  para: {
                    code: code
                  }
              }
              that.requestSdk({
                param: param,
                success: userRes => {
                  if (userRes.code == 1000) {
                      if(userRes.body.authSuccess) {
                        this.getCode(function (codeHooves) {
                          that.globalData.userInfo = Object.assign({},
                            res.userInfo,
                            {code: codeHooves},
                            {openId: userRes.body.openId}
                          )
                          that.setUserInfo(that.globalData.userInfo)
                          typeof callback == "function" && callback(that.globalData.userInfo);
                        })
                      } else {
                        that.toastAuthFailModal();
                      }                   
                  }
                },
                fail: data => {
                  wx.hideToast();
                  console.log("获取用户信息-失败", data);
                  wx.showModal({
                    title: '提示-测试',
                    content: '用户登录失败，请稍后再试',
                    showCancel: false,
                  })
                },
                complete: data => {
                  console.log("获取用户信息-完成", data);
                }
              });
            },
            fail: (res) => {
              wx.hideToast();
              console.log("wx.getUserInfo 接口调用失败", res);
              if (!that.globalData.hintAuthorize) {
                that.globalData.hintAuthorize = true;
                wx.showModal({
                  title: '提示',
                  content: '您已拒绝授权。本小程序需要授权后才能使用，请稍后再试。',
                  showCancel: false,
                })
              }
            }
          });
        },
        fail: (res) => {
          console.log("wx.login 接口调用失败", res);
          wx.showModal({
            title: '提示',
            content: '登录调用失败',
            showCancel: false,
          })
        }
      });
    }
  },

  getCode: function (callBack) {
	  wx.login({
		  success: function (res) {
        typeof callBack == 'function'&& callBack(res.code)
		  }
	  })
  },
  requestSdkForNeedLogin: function (params) {
    console.log("请求-requestSdkForNeedLogin", params);
    //需要登录的请求接口
    let request = {
      param: params.param,
      beforeSend: params.beforeSend,
      success: params.success,
      fail: params.fail,
      complete: params.complete
    }
    request.param.para = request.param.para || {};
    //如果没有传入 userType 则加上 userType
    if (!request.param.para.userType) {
      request.param.para.userType = "WeiXinApp";
    }

    //如果没有传入 userId 则加上 userId
    if (!request.param.para.WX_OPENID) {
      this.getUserInfo(userInfo => {
        request.param.para.userId = userInfo.openId;
        request.param.para.WX_OPENID = userInfo.openId;
        this.requestSdk(request);


      });
    }
    else {
      this.requestSdk(request);
    }
  },
  requestSdk: function (params) {
    console.log("请求-requestSdk：", params);
    //通用的请求接口
    let request = {
      url: params.param.url,
      param: params.param.para,
      beforeSend: params.beforeSend,
      success: params.success,
      fail: params.fail,
      complete: params.complete
    }
      request.param['WX_CHANNEL'] = this.globalData.channelId || '';
    typeof request.beforeSend == "function" && request.beforeSend();

     
    wx.request({
      url: this.globalData.GateWay+request.url,
      method: "POST",
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: request.param,  //JSON.stringify(request.param),
    
      success: function (res) {
        typeof request.success == "function" && request.success(res.data);

      },
      fail: function (res) {
        console.log("请求-requestSdk-fail：", res);
        if (typeof request.fail == "function")
          request.fail(res);
        else {
          //弹窗
          wx.showModal({
            title: '提示',
            content: '网络请求错误',
            showCancel: false,
          })
        }
      },
      complete: function (res) {
        typeof request.complete == "function" && request.complete(res.data);
      }
    });
  },
  deepClone: function (obj) {  // 深度克隆
    return JSON.parse(JSON.stringify(obj));
  },
	//时间戳转换时间
	 toYMDDate:function(number){
      var n = number;
      var date = new Date(n);
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
      var D = date.getDate()<10 ? '0'+date.getDate() : date.getDate();
      return Y + M +  D;
   },
  //时间戳转换时间
   toYMDHMSDate:function(number){
    var n = number;
    var date = new Date(n);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    var D = date.getDate()<10 ? '0'+date.getDate() : date.getDate();
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return Y + M +  D+' '+h+':'+minute+':'+second;
  },
	isAndroid:function () {
		var res = wx.getSystemInfoSync()
		if(res.model.indexOf('iPhone')>-1){
			return false;
		}else {
			return true;
		}
	},
  //微信支付
   requestPayment:function(opt) {
    wx.requestPayment({
      'timeStamp': opt.timeStamp,
      'nonceStr': opt.nonceStr,
      'package': opt.package,
      'signType':opt.signType,
      'paySign': opt.paySign,
      'success':function(res){
        if(opt.sucFn!=null&&opt.sucFn!="" &&typeof(opt.sucFn)!="undefined"){
          opt.sucFn(res);
        }
      },
      'fail':function(res){
        if(opt.failFn!=null&&opt.failFn!="" &&typeof(opt.failFn)!="undefined"){
          opt.failFn(res);
        }
      }
    })
  },

  uploadFile :function(opt) {
	if(opt.showLoadFlag=="true"){
		if(compareAppVersionToTarget(getSystemInfoSync().SDKVersion, "1.1.0")){
			wx.showLoading({title: '正在上传',mask:true});
		}else{
			wx.showToast({
				title: '正在上传',
				icon: 'loading',
				duration: 60000,
				mask: true
			});
		}
	}
  this.noneNetwork();
    console.log('正在上传')
	wx.uploadFile({
		url: Host+"/com/upload.ajax",
		filePath: opt.filePath,
		name: 'file',
		header: { "Content-Type": "multipart/form-data" },
		formData:opt.params,
		success: function (res) {
			if (!(opt.success==null || opt.success=="" || typeof(opt.success)=="undefined")){
				opt.success(res);
			}
		},
		fail: function (res) {
			if (!(opt.fail==null || opt.fail=="" || typeof(opt.fail)=="undefined")){
				opt.fail(res);
			}
		},
		complete:function (res) {
      console.log('兑换图片接口返回的数据',res)
			if(opt.showLoadFlag=="true"){
				if(compareAppVersionToTarget(getSystemInfoSync().SDKVersion, "1.1.0")){
					wx.hideLoading();
				}else{
					wx.hideToast();
				}
			}
		}
	})
},
 noneNetwork:function() {
	wx.getNetworkType({
		success: function (res) {
			var networkType = res.networkType;
			if(networkType=='none'){
				wx.showModal({
					title: "温馨提示",
					content: "网络超时，请检查网络设置",
					showCancel: false,
					confirmText: "确定",
					success: function (res) {
					}
				});
				return false;
			}
		}
	});
},
crossToUrl:function (res) {
  if (wx.navigateToMiniProgram) {
  wx.navigateToMiniProgram({
    appId: res.appid,
    path: res.path,
    envVersion: res.envVersion,
    success:function(data) {
      console.log('跳转成功',data)
    },
    fail:function(data){
      console.log('跳转失败',data)
    }
  })
  } else {
  // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
  wx.showModal({
    title: '提示',
    content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
  })
  }
},
redirectTo:function (data) {
  wx.redirectTo({
  url: data.url,
  success: function(res){
      if (!(data.success==null || data.success=="" || typeof(data.success)=="undefined")){
          data.success(res);
      }
  },
  fail: function() {
      if (!(data.fail==null || data.fail=="" || typeof(data.fail)=="undefined")){
          data.fail(res);
      }
  },
  complete: function() {
      if (!(data.complete==null || data.complete=="" || typeof(data.complete)=="undefined")){
           data.complete(res);
      }
  }
  })
}
})